package com.easylive.app.video;

import android.content.Context;
import android.graphics.Outline;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.aliyun.player.AliPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.bean.ErrorInfo;
import com.aliyun.player.bean.InfoBean;
import com.aliyun.player.bean.InfoCode;
import com.aliyun.player.nativeclass.CacheConfig;
import com.aliyun.player.nativeclass.MediaInfo;
import com.aliyun.player.nativeclass.PlayerConfig;
import com.aliyun.player.nativeclass.TrackInfo;
import com.aliyun.player.source.UrlSource;
import com.aliyun.thumbnail.ThumbnailHelper;
import com.aliyun.utils.VcPlayerLog;
import com.easylive.app.video.control.ControlView;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UI播放器的主要实现类。 通过ITheme控制各个界面的主题色。 通过各种view的组合实现UI的界面。
 * 这些view包括： 用户手势操作的{@linkGestureView} 控制播放，
 * 显示信息的{@linkControlView}
 * 显示清晰度列表的{@linkQualityView}
 * 倍速选择界面{@linkSpeedView}
 * 用户使用引导页面{@linkGuideView}
 * 用户提示页面{@linkTipsView}
 * 以及封面等。 view 的初始化是在{@link #initVideoView}方法中实现的。
 * 然后是对各个view添加监听方法，处理对应的操作，从而实现与播放器的共同操作
 */
public class VideoPlayerView extends RelativeLayout {
    /**
     * 精准seek开启判断逻辑：当视频时长小于5分钟的时候。
     */
    private static final int ACCURATE = 5 * 60 * 1000;
    private static final String TAG = VideoPlayerView.class.getSimpleName();
    private static VideoPlayerView playerView;
    //当前屏幕模式
    ScreenMode mCurrentScreenMode = ScreenMode.Small;
    /**
     * 判断VodePlayer 是否加载完成
     */
    private Map<MediaInfo, Boolean> hasLoadEnd = new HashMap<>();
    //视频画面
    private SurfaceView mSurfaceView;
    private ControlView mControlView;
    //封面view
    private ImageView mCoverView;
    //播放器
    private AliPlayer mAliyunVodPlayer;
    //网络状态监听
    private NetWatchdog mNetWatchdog;
    //是不是在seek中
    private boolean inSeek = false;
    //播放是否完成
    private boolean isCompleted = false;
    //媒体信息
    private MediaInfo mAliyunMediaInfo;
    //解决bug,进入播放界面快速切换到其他界面,播放器仍然播放视频问题
    private VodPlayerLoadEndHandler vodPlayerLoadEndHandler = new VodPlayerLoadEndHandler(this);
    //原视频的buffered
    private long mVideoBufferedPosition = 0;
    //原视频的currentPosition
    private long mCurrentPosition = 0;
    //当前播放器的状态 默认为idle状态
    private int mPlayerState = IPlayer.idle;
    //原视频时长
    private long mSourceDuration;
//    private VidSts mAliyunVidSts;
    //目前支持的几种播放方式
//    private VidAuth mAliyunPlayAuth;
    private UrlSource mAliyunLocalSource;
    //对外的各种事件监听
    private IPlayer.OnInfoListener mOutInfoListener = null;
    private IPlayer.OnErrorListener mOutErrorListener = null;
    //    private IPlayer.OnRePlayListener mOutRePlayListener = null;
    private IPlayer.OnPreparedListener mOutPreparedListener = null;
    private IPlayer.OnCompletionListener mOutCompletionListener = null;
    private IPlayer.OnSeekCompleteListener mOuterSeekCompleteListener = null;
    private IPlayer.OnRenderingStartListener mOutFirstFrameStartListener = null;
    private OnScreenBrightnessListener mOnScreenBrightnessListener = null;
    private OnTimeExpiredErrorListener mOutTimeExpiredErrorListener = null;
    //    private IPlayer.OnUrlTimeExpiredListener mOutUrlTimeExpiredListener = null;
    // 连网断网监听
    private NetConnectedListener mNetConnectedListener = null;
    //播放按钮点击监听
    private OnPlayStateBtnClickListener onPlayStateBtnClickListener;
    //停止按钮监听
    private OnStoppedListener mOnStoppedListener;
    //当前屏幕亮度
    private int mScreenBrightness;
    /**
     * 缩略图帮助类
     */
    private ThumbnailHelper mThumbnailHelper;
    //获取缩略图是否成功
    private boolean mThumbnailPrepareSuccess = false;
    private float currentSpeed;
    private float currentVolume;
    private int currentScreenBrigtness;
    private List<String> mVideoSourceList = new ArrayList<>();
    private int mCurVideoIdx = 0;
    private OnBackListener onBackListener;
    private OnSeekListener onSeekListener;
    private OnSwitchScreenModeStatus onSwitchScreenModeStatus;

    public VideoPlayerView(Context context) {
        super(context);
        initVideoView();
        playerView = this;
    }

    public VideoPlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initVideoView();
        playerView = this;
    }

    public VideoPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initVideoView();
        playerView = this;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public VideoPlayerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initVideoView();
        playerView = this;
    }

    public static VideoPlayerView getInstans(Context context) {
        if (playerView == null) {
            playerView = new VideoPlayerView(context);
        }
        return playerView;
    }

    /**
     * 初始化view
     */
    private void initVideoView() {
        //初始化播放用的surfaceView
        initSurfaceView();
        //初始化播放器
        initAliVcPlayer();
        //初始化封面
        //initCoverView();
        //初始化控制栏
        //initControlView();
        //初始化网络监听器
        initNetWatchdog();

        //初始化手势对话框控制
//        initGestureDialogManager();
        //先隐藏手势和控制栏，防止在没有prepare的时候做操作。
        //hideGestureAndControlViews();
    }

    public float getCurrentSpeed() {
        return currentSpeed;
    }

    public void setCurrentSpeed(float currentSpeed) {
        this.currentSpeed = currentSpeed;
    }

    public float getCurrentVolume() {
        if (mAliyunVodPlayer != null) {
            return mAliyunVodPlayer.getVolume();
        }
        return 0;
    }

    public void setCurrentVolume(float progress) {
        this.currentVolume = progress;
        mAliyunVodPlayer.setVolume(progress);
    }

    public void updateScreenShow() {
    }

    /**
     * 隐藏控制栏
     */
    private void hideGestureAndControlViews() {
        if (mControlView != null) {
            mControlView.show();
            mControlView.hide(ViewAction.HideType.Normal);
        }
    }

    /**
     * 初始化网络监听
     */
    private void initNetWatchdog() {
        Context context = getContext();
        mNetWatchdog = new NetWatchdog(context);
        mNetWatchdog.setNetChangeListener(new MyNetChangeListener(this));
        mNetWatchdog.setNetConnectedListener(new MyNetConnectedListener(this));
    }

    private void onNetDisconnected() {
        VcPlayerLog.d(TAG, "onNetDisconnected");
        //网络断开。
        // NOTE： 由于安卓这块网络切换的时候，有时候也会先报断开。所以这个回调是不准确的。
    }

    /**
     * 重试播放，会从当前位置开始播放
     */
    public void reTry() {

        isCompleted = false;
        inSeek = false;

        int currentPosition = mControlView.getVideoPosition();
        VcPlayerLog.d(TAG, " currentPosition = " + currentPosition);

        if (mControlView != null) {
            mControlView.reset();
            //防止被reset掉，下次还可以获取到这些值
            mControlView.setVideoPosition(currentPosition);
        }

        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.setDataSource(mAliyunLocalSource);
            mAliyunVodPlayer.prepare();
            isAutoAccurate(currentPosition);
        }

    }

    /**
     * 重置。包括一些状态值，view的状态等
     */
    private void reset() {
        isCompleted = false;
        inSeek = false;
        mCurrentPosition = 0;
        mVideoBufferedPosition = 0;

        if (mControlView != null) {
            mControlView.reset();
        }
        stop();
    }

    /**
     * 初始化封面
     */
    private void initCoverView() {
        mCoverView = new ImageView(getContext());
        //这个是为了给自动化测试用的id
//        mCoverView.setId(R.id.custom_id_min);
        addSubView(mCoverView);
    }

    /**
     * 初始化控制栏view
     */
    private void initControlView() {
        mControlView = new ControlView(getContext());
        addSubView(mControlView);
        //设置播放按钮点击
        mControlView.setOnPlayStateClickListener(new ControlView.OnPlayStateClickListener() {
            @Override
            public void onPlayStateClick() {
                switchPlayerState();
            }
        });
        //设置进度条的seek监听
        mControlView.setOnSeekListener(new ControlView.OnSeekListener() {
            @Override
            public void onSeekEnd(int position) {

                if (mControlView != null) {
                    mControlView.setVideoPosition(position);
                }
                if (isCompleted) {
                    //播放完成了，不能seek了
                    inSeek = false;
                } else {
                    //拖动结束后，开始seek
                    seekTo(position);

                    if (onSeekListener != null) {
                        onSeekListener.onSeekComplete(position);
                    }
                }
            }

            @Override
            public void onSeekStart(int position) {
                //拖动开始
                inSeek = true;
                if (onSeekListener != null) {
                    onSeekListener.onSeekStart(position);
                }

            }

            @Override
            public void onProgressChanged(int progress, boolean fromUser) {
                if (fromUser) {
                }
            }
        });

        //点击全屏/小屏按钮
        mControlView.setOnScreenModeClickListener(new ControlView.OnScreenModeClickListener() {
            @Override
            public void onClick() {
                ScreenMode targetMode;
                if (mCurrentScreenMode == ScreenMode.Small) {
                    targetMode = ScreenMode.Full;
                } else {
                    targetMode = ScreenMode.Small;
                }

                changeScreenMode(targetMode, false);
            }
        });
        //点击了标题栏的返回按钮
        mControlView.setOnBackClickListener(new ControlView.OnBackClickListener() {
            @Override
            public void onClick() {
                if (onBackListener != null) {
                    onBackListener.onBackListener();
                }
//                if (mCurrentScreenMode == ScreenMode.Full) {
//                    //设置为小屏状态
//                    changeScreenMode(ScreenMode.Small, false);
//                } else if (mCurrentScreenMode == ScreenMode.Small) {
//                    //小屏状态下，就结束活动
//                    Context context = getContext();
//                    if (context instanceof Activity) {
//                        ((Activity) context).finish();
//                    }
//                }

            }
        });

        mControlView.setOnSmallClickListener(new ControlView.OnSmallClickListener() {
            @Override
            public void onClick() {
                if (mCurrentScreenMode == ScreenMode.Full) {
                    changeScreenMode(ScreenMode.Small, false);
                }
            }
        });

    }

    /**
     * 保持屏幕常亮
     *
     * @param keepScreenOn
     */
    @Override
    public void setKeepScreenOn(boolean keepScreenOn) {
        super.setKeepScreenOn(true);
    }

    /**
     * 目标位置计算算法
     *
     * @param duration        视频总时长
     * @param currentPosition 当前播放位置
     * @param deltaPosition   与当前位置相差的时长
     * @return
     */
    public int getTargetPosition(long duration, long currentPosition, long deltaPosition) {
        // seek步长
        long finalDeltaPosition;
        // 根据视频时长，决定seek步长
        long totalMinutes = duration / 1000 / 60;
        int hours = (int) (totalMinutes / 60);
        int minutes = (int) (totalMinutes % 60);

        // 视频时长为1小时以上，小屏和全屏的手势滑动最长为视频时长的十分之一
        if (hours >= 1) {
            finalDeltaPosition = deltaPosition / 10;
        }// 视频时长为31分钟－60分钟时，小屏和全屏的手势滑动最长为视频时长五分之一
        else if (minutes > 30) {
            finalDeltaPosition = deltaPosition / 5;
        }// 视频时长为11分钟－30分钟时，小屏和全屏的手势滑动最长为视频时长三分之一
        else if (minutes > 10) {
            finalDeltaPosition = deltaPosition / 3;
        }// 视频时长为4-10分钟时，小屏和全屏的手势滑动最长为视频时长二分之一
        else if (minutes > 3) {
            finalDeltaPosition = deltaPosition / 2;
        }// 视频时长为1秒钟至3分钟时，小屏和全屏的手势滑动最长为视频结束
        else {
            finalDeltaPosition = deltaPosition;
        }

        long targetPosition = finalDeltaPosition + currentPosition;
        if (targetPosition < 0) {
            targetPosition = 0;
        }
        if (targetPosition > duration) {
            targetPosition = duration;
        }
        return (int) targetPosition;
    }

    /**
     * 切换播放状态。点播播放按钮之后的操作
     */
    public void switchPlayerState() {
        if (onPlayStateBtnClickListener != null) {
            onPlayStateBtnClickListener.onPlayBtnClick(mPlayerState);
        }
        if (mPlayerState == IPlayer.started) {
            pause();

        } else if (mPlayerState == IPlayer.paused || mPlayerState == IPlayer.prepared) {
            start();
        }

    }

    /**
     * 切换播放状态。点播播放按钮之后的操作
     */
    public void switchPlayerStart() {

        if (mPlayerState == IPlayer.paused || mPlayerState == IPlayer.prepared) {
            start();
            if (onPlayStateBtnClickListener != null) {
                onPlayStateBtnClickListener.onPlayBtnClick(mPlayerState);
            }
        }

    }

    /**
     * 初始化播放器显示view
     */
    private void initSurfaceView() {
        mSurfaceView = new SurfaceView(getContext().getApplicationContext());
        mSurfaceView.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                Rect rect = new Rect();
                view.getGlobalVisibleRect(rect);
                int leftMargin = 0;
                int topMargin = 0;
                Rect selfRect = new Rect(leftMargin, topMargin,
                        rect.right - rect.left - leftMargin,
                        rect.bottom - rect.top - topMargin);
                outline.setRoundRect(selfRect, 14);
            }
        });
        mSurfaceView.setClipToOutline(true);

        addSubView(mSurfaceView);

        SurfaceHolder holder = mSurfaceView.getHolder();
        //增加surfaceView的监听
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                VcPlayerLog.d(TAG, " surfaceCreated = surfaceHolder = " + surfaceHolder);
                if (mAliyunVodPlayer != null) {
                    mAliyunVodPlayer.setDisplay(surfaceHolder);
                    //防止黑屏
                    mAliyunVodPlayer.redraw();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width,
                                       int height) {
                VcPlayerLog.d(TAG,
                        " surfaceChanged surfaceHolder = " + surfaceHolder + " ,  width = " + width + " , height = "
                                + height);
                if (mAliyunVodPlayer != null) {
                    mAliyunVodPlayer.redraw();
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                VcPlayerLog.d(TAG, " surfaceDestroyed = surfaceHolder = " + surfaceHolder);
                if (mAliyunVodPlayer != null) {
                    mAliyunVodPlayer.setDisplay(null);
                }
            }
        });
    }

    private CacheConfig getCacheConfig(Context ctx) {
        CacheConfig cacheConfig = new CacheConfig();
        cacheConfig.mEnable = true;
        String cachePath = "/data/data/" + ctx.getPackageName() + "/media/video/";
        File cacheFile = new File(cachePath);
        if (!cacheFile.exists()) {
            cacheFile.mkdirs();
        }
        cacheConfig.mDir = cachePath;
        cacheConfig.mMaxDurationS = 60 * 60 * 24;
        cacheConfig.mMaxSizeMB = 1024;
        Log.d(TAG, "cache dir:" + cacheConfig.mDir);
        return cacheConfig;
    }

    /**
     * 初始化播放器
     */
    private void initAliVcPlayer() {
        mAliyunVodPlayer = AliPlayerFactory.createAliPlayer(getContext().getApplicationContext());
        mAliyunVodPlayer.enableLog(false);
        mAliyunVodPlayer.setCacheConfig(getCacheConfig(getContext()));
        //设置准备回调
        mAliyunVodPlayer.setOnPreparedListener(new VideoPlayerPreparedListener(this));
        //播放器出错监听
        mAliyunVodPlayer.setOnErrorListener(new VideoPlayerErrorListener(this));
        //播放器加载回调
        mAliyunVodPlayer.setOnLoadingStatusListener(new VideoPlayerLoadingStatusListener(this));
        //播放器状态
        mAliyunVodPlayer.setOnStateChangedListener(new VideoPlayerStateChangedListener(this));
        //播放结束
        mAliyunVodPlayer.setOnCompletionListener(new VideoPlayerCompletionListener(this));
        //播放信息监听
        mAliyunVodPlayer.setOnInfoListener(new VideoPlayerInfoListener(this));
        //第一帧显示
        mAliyunVodPlayer.setOnRenderingStartListener(new VideoPlayerRenderingStartListener(this));
        //trackChange监听
        mAliyunVodPlayer.setOnTrackChangedListener(new VideoPlayerTrackChangedListener(this));
        //seek结束事件
        mAliyunVodPlayer.setOnSeekCompleteListener(new VideoPlayerOnSeekCompleteListener(this));
        mAliyunVodPlayer.setDisplay(mSurfaceView.getHolder());
    }

    /**
     * 获取从源中设置的标题 。 如果用户设置了标题，优先使用用户设置的标题。 如果没有，就使用服务器返回的标题
     *
     * @param title 服务器返回的标题
     * @return 最后的标题
     */
    private String getTitle(String title) {
        String finalTitle = title;
        if (mAliyunLocalSource != null) {
            finalTitle = mAliyunLocalSource.getTitle();
        }

        if (TextUtils.isEmpty(finalTitle)) {
            return title;
        } else {
            return finalTitle;
        }
    }

    /**
     * 获取当前位置
     *
     * @return 当前位置
     */
//    public int getCurrentPosition() {
//        if (mAliyunVodPlayer != null && mAliyunVodPlayer.isPlaying()) {
//            return (int) mAliyunVodPlayer.getCurrentPosition();
//        }
//
//        return 0;
//    }

    /**
     * 获取从源中设置的封面 。 如果用户设置了封面，优先使用用户设置的封面。 如果没有，就使用服务器返回的封面
     *
     * @param postUrl 服务器返回的封面
     * @return 最后的封面
     */
    private String getPostUrl(String postUrl) {
        String finalPostUrl = postUrl;
        if (mAliyunLocalSource != null) {
            finalPostUrl = mAliyunLocalSource.getCoverPath();
        }
//        else if (mAliyunPlayAuth != null) {
//
//        }

        if (TextUtils.isEmpty(finalPostUrl)) {
            return postUrl;
        } else {
            return finalPostUrl;
        }
    }

    /**
     * 获取视频时长
     *
     * @return 视频时长
     */
    public int getDuration() {
        if (mAliyunVodPlayer != null) {
            return (int) mAliyunVodPlayer.getDuration();
        }

        return 0;
    }

    /**
     * 显示错误提示
     *
     * @param errorCode  错误码
     * @param errorEvent 错误事件
     * @param errorMsg   错误描述
     */
    public void showErrorTipView(int errorCode, String errorEvent, String errorMsg) {
        pause();
        stop();
        if (mControlView != null) {
            mControlView.setPlayState(ControlView.PlayState.NotPlaying);
        }
        Log.d(TAG, "播放错误：" + errorMsg);
        Toast.makeText(getContext(), "播放失败...", Toast.LENGTH_LONG).show();
    }

    /**
     * addSubView 添加子view到布局中
     *
     * @param view 子view
     */
    private void addSubView(View view) {
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        //添加到布局中
        addView(view, params);
    }

    /**
     * 添加子View到布局中央
     */
    private void addSubViewByCenter(View view) {
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        addView(view, params);
    }

    /**
     * 添加子View到布局中,在某个View的下方
     *
     * @param view            需要添加的View
     * @param belowTargetView 在这个View的下方
     */
    private void addSubViewBelow(final View view, final View belowTargetView) {
        belowTargetView.post(new Runnable() {
            @Override
            public void run() {
                LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                int measuredHeight = belowTargetView.getMeasuredHeight();
                params.topMargin = measuredHeight;
                //添加到布局中
                addView(view, params);
            }
        });
    }

    /**
     * 改变屏幕模式：小屏或者全屏。
     *
     * @param targetMode
     */
    public void changeScreenMode(ScreenMode targetMode, boolean isReverse) {
        VcPlayerLog.d(TAG, "mIsFullScreenLocked = " + " ， targetMode = " + targetMode);

        ScreenMode finalScreenMode = targetMode;

//        finalScreenMode = ScreenMode.Full;

        //这里可能会对模式做一些修改
        if (targetMode != mCurrentScreenMode) {
            mCurrentScreenMode = finalScreenMode;
        }

        if (mControlView != null) {
            mControlView.setScreenModeStatus(finalScreenMode);
            if (onSwitchScreenModeStatus != null) {
                onSwitchScreenModeStatus.Switch(mCurrentScreenMode);
            }
        }


//        Context context = getContext();
//        if (context instanceof Activity) {
//            if (finalScreenMode == ScreenMode.Full) {
//                //如果是固定全屏，那么直接设置view的布局，宽高
//                ViewGroup.LayoutParams aliVcVideoViewLayoutParams = getLayoutParams();
//                aliVcVideoViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
//                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
//            } else if (finalScreenMode == ScreenMode.Small) {
//
//
//                //如果是固定全屏，那么直接设置view的布局，宽高
//                ViewGroup.LayoutParams aliVcVideoViewLayoutParams = getLayoutParams();
////                    aliVcVideoViewLayoutParams.height = (int) (ScreenUtils.getWidth(context) * 9.0f / 16);
//                aliVcVideoViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
//                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
//            }
//        }
    }

    /**
     * 获取当前屏幕模式：小屏、全屏
     *
     * @return 当前屏幕模式
     */
    public ScreenMode getScreenMode() {
        return mCurrentScreenMode;
    }

    /**
     * 设置准备事件监听
     *
     * @param onPreparedListener 准备事件
     */
    public void setOnPreparedListener(IPlayer.OnPreparedListener onPreparedListener) {
        mOutPreparedListener = onPreparedListener;
    }

    /**
     * 设置错误事件监听
     *
     * @param onErrorListener 错误事件监听
     */
    public void setOnErrorListener(IPlayer.OnErrorListener onErrorListener) {
        mOutErrorListener = onErrorListener;
    }

    /**
     * 设置信息事件监听
     *
     * @param onInfoListener 信息事件监听
     */
    public void setOnInfoListener(IPlayer.OnInfoListener onInfoListener) {
        mOutInfoListener = onInfoListener;
    }

    /**
     * 设置播放完成事件监听
     *
     * @param onCompletionListener 播放完成事件监听
     */
    public void setOnCompletionListener(IPlayer.OnCompletionListener onCompletionListener) {
        mOutCompletionListener = onCompletionListener;
    }

    public void setOnBackListener(OnBackListener onBackListener) {
        this.onBackListener = onBackListener;
    }

    /**
     * 设置源超时监听
     *
     * @param l 源超时监听
     */
    public void setOnTimeExpiredErrorListener(OnTimeExpiredErrorListener l) {
        mOutTimeExpiredErrorListener = l;
    }

    /**
     * 设置首帧显示事件监听
     *
     * @param onFirstFrameStartListener 首帧显示事件监听
     */
    public void setOnFirstFrameStartListener(IPlayer.OnRenderingStartListener onFirstFrameStartListener) {
        mOutFirstFrameStartListener = onFirstFrameStartListener;
    }

    /**
     * 设置鉴权过期监听，在鉴权过期前一分钟回调
     *
     * @param listener
     */
//    public void setOnUrlTimeExpiredListener(IPlayer.OnUrlTimeExpiredListener listener) {
//        this.mOutUrlTimeExpiredListener = listener;
//    }

    /**
     * 设置seek结束监听
     *
     * @param onSeekCompleteListener seek结束监听
     */
    public void setOnSeekCompleteListener(IPlayer.OnSeekCompleteListener onSeekCompleteListener) {
        mOuterSeekCompleteListener = onSeekCompleteListener;
    }

    /**
     * 设置停止播放监听
     *
     * @param onStoppedListener 停止播放监听
     */
    public void setOnStoppedListener(OnStoppedListener onStoppedListener) {
        this.mOnStoppedListener = onStoppedListener;
    }

    /**
     * 设置加载状态监听
     *
     * @param onLoadingListener 加载状态监听
     */
    public void setOnLoadingListener(IPlayer.OnLoadingStatusListener onLoadingListener) {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.setOnLoadingStatusListener(onLoadingListener);
        }
    }

    /**
     * 设置视频宽高变化监听
     *
     * @param onVideoSizeChangedListener 视频宽高变化监听
     */
    public void setOnVideoSizeChangedListener(IPlayer.OnVideoSizeChangedListener onVideoSizeChangedListener) {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.setOnVideoSizeChangedListener(onVideoSizeChangedListener);
        }
    }

    /**
     * 清空之前设置的播放源
     */
    private void clearAllSource() {
//        mAliyunPlayAuth = null;
//        mAliyunVidSts = null;
        mAliyunLocalSource = null;
    }

    /**
     * 设置封面信息
     *
     * @param uri url地址
     */
    public void setCoverUri(String uri) {
        if (mCoverView != null && !TextUtils.isEmpty(uri)) {
            (new ImageLoader(mCoverView)).loadAsync(uri);
            mCoverView.setVisibility(isPlaying() ? GONE : VISIBLE);
        }
    }

    /**
     * 设置封面id
     *
     * @param resId 资源id
     */
    public void setCoverResource(int resId) {
        if (mCoverView != null) {
            mCoverView.setImageResource(resId);
            mCoverView.setVisibility(isPlaying() ? GONE : VISIBLE);
        }
    }

    /**
     * 设置缩放模式
     *
     * @param scallingMode 缩放模式
     */
    public void setVideoScalingMode(IPlayer.ScaleMode scallingMode) {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.setScaleMode(scallingMode);
        }
    }

    /**
     * 在activity调用onResume的时候调用。 解决home回来后，画面方向不对的问题
     */
    public void onResume() {
        Log.d("bob", "player onResume");
        if (mNetWatchdog != null) {
            mNetWatchdog.startWatch();
        }


        //从其他界面过来的话，也要show。
//        if (mControlView != null) {
//            mControlView.show();
//        }

        //onStop中记录下来的状态，在这里恢复使用
        resumePlayerState();
    }

    /**
     * 暂停播放器的操作
     */
    public void onStop() {
        if (mNetWatchdog != null) {
            mNetWatchdog.stopWatch();
        }
        stop();
        //保存播放器的状态，供resume恢复使用。
//        savePlayerState();
    }

    /**
     * Activity回来后，恢复之前的状态
     */
    private void resumePlayerState() {
        if (mAliyunVodPlayer == null) {
            return;
        }
        //恢复前台后需要进行判断,如果是本地资源,则继续播放,如果是4g则给予提示,不会继续播放,否则继续播放

        start();


    }

    /**
     * 保存当前的状态，供恢复使用
     */
    private void savePlayerState() {
        if (mAliyunVodPlayer == null) {
            return;
        }
        //然后再暂停播放器
        //如果希望后台继续播放，不需要暂停的话，可以注释掉pause调用。
        pause();
    }

    /**
     * 获取媒体信息
     *
     * @return 媒体信息
     */
    public MediaInfo getMediaInfo() {
        if (mAliyunVodPlayer != null) {
            return mAliyunVodPlayer.getMediaInfo();
        }

        return null;
    }

    /**
     * 活动销毁，释放
     */
    public void onDestroy() {
        stop();
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.release();
            mAliyunVodPlayer = null;
        }

        mSurfaceView = null;
        mControlView = null;
        mCoverView = null;
        if (mNetWatchdog != null) {
            mNetWatchdog.stopWatch();
        }
        mNetWatchdog = null;
        mAliyunMediaInfo = null;

        if (hasLoadEnd != null) {
            hasLoadEnd.clear();
        }
    }

    /**
     * 是否处于播放状态：start或者pause了
     *
     * @return 是否处于播放状态
     */
    public boolean isPlaying() {
        return mPlayerState == IPlayer.started;
    }

    /**
     * 获取播放器状态
     *
     * @return 播放器状态
     */
    public int getPlayerState() {
        return mPlayerState;
    }

    /**
     * 开始播放
     */
    public void start() {
        if (!mVideoSourceList.isEmpty()) {
            if (mCurVideoIdx >= mVideoSourceList.size()) {
                mCurVideoIdx = 0;
            }
            setLocalSource(mVideoSourceList.get(mCurVideoIdx));
        }
        if (mControlView != null) {
            mControlView.show();
            mControlView.setPlayState(ControlView.PlayState.Playing);
        }

        if (mAliyunVodPlayer == null) {
            return;
        }

        if (mPlayerState == IPlayer.paused || mPlayerState == IPlayer.prepared) {
            mAliyunVodPlayer.start();
        }

    }

    /**
     * 暂停播放
     */
    public void pause() {
        if (mControlView != null) {
            mControlView.setPlayState(ControlView.PlayState.NotPlaying);
        }
        if (mAliyunVodPlayer == null) {
            return;
        }

        if (mPlayerState == IPlayer.started || mPlayerState == IPlayer.prepared) {
            mAliyunVodPlayer.pause();
        }
    }

    /**
     * 停止播放
     */
    private void stop() {
        Boolean hasLoadedEnd = null;
        MediaInfo mediaInfo = null;
        clearAllSource();
        if (mAliyunVodPlayer != null && hasLoadEnd != null) {
            mediaInfo = mAliyunVodPlayer.getMediaInfo();
            hasLoadedEnd = hasLoadEnd.get(mediaInfo);
        }

        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.stop();
        }

        if (mControlView != null) {
            mControlView.setPlayState(ControlView.PlayState.NotPlaying);
        }
        if (hasLoadEnd != null) {
            hasLoadEnd.remove(mediaInfo);
        }
    }

    /**
     * seek操作
     *
     * @param position 目标位置
     */
    public void seekTo(int position) {
        if (mAliyunVodPlayer == null) {
            return;
        }
        inSeek = true;
        realySeekToFunction(position);
    }

    private void realySeekToFunction(int position) {
        isAutoAccurate(position);
        mAliyunVodPlayer.start();
        if (mControlView != null) {
            mControlView.setPlayState(ControlView.PlayState.Playing);
        }
    }

    /**
     * 判断是否开启精准seek
     */
    private void isAutoAccurate(int position) {
        if (getDuration() <= ACCURATE) {
            mAliyunVodPlayer.seekTo(position);
        } else {
            mAliyunVodPlayer.seekTo(position, IPlayer.SeekMode.Inaccurate);
        }
    }

    /**
     * 设置是否显示控制栏
     *
     * @param show true:是
     */
    public void setControlBarCanShow(boolean show) {
        if (mControlView != null) {
            mControlView.setControlBarCanShow(show);
        }

    }

    /**
     * 开启底层日志
     */
    public void enableNativeLog() {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.enableLog(true);
        }
    }

    /**
     * 关闭底层日志
     */
    public void disableNativeLog() {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.enableLog(false);
        }
    }

    /**
     * 获取SDK版本号
     *
     * @return SDK版本号
     */
    public String getSDKVersion() {
        return AliPlayerFactory.getSdkVersion();
    }

    /**
     * 获取播放surfaceView
     *
     * @return 播放surfaceView
     */
    public SurfaceView getPlayerView() {
        return mSurfaceView;
    }

    /**
     * 设置自动播放
     *
     * @param auto true 自动播放
     */
    public void setAutoPlay(boolean auto) {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.setAutoPlay(auto);
        }
    }

    /**
     * 获取底层的一些debug信息
     *
     * @return debug信息
     */
    public Map<String, String> getAllDebugInfo() {
        if (mAliyunVodPlayer != null) {
//            return mAliyunVodPlayer.getAllDebugInfo();
        }
        return null;
    }

    /**
     * 截图功能
     *
     * @return 图片
     */
    public void snapShot() {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.snapshot();
        }
    }

    /**
     * 设置循环播放
     *
     * @param circlePlay true:循环播放
     */
    public void setCirclePlay(boolean circlePlay) {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.setLoop(circlePlay);
        }
    }

    /**
     * 设置播放时的镜像模式
     *
     * @param mode 镜像模式
     */
    public void setRenderMirrorMode(IPlayer.MirrorMode mode) {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.setMirrorMode(mode);
        }
    }

    /**
     * 设置播放时的旋转方向
     *
     * @param rotate 旋转角度
     */
    public void setRenderRotate(IPlayer.RotateMode rotate) {
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.setRotateMode(rotate);
        }
    }

    /**
     * 设置播放状态点击监听
     */
    public void setOnPlayStateBtnClickListener(OnPlayStateBtnClickListener listener) {
        this.onPlayStateBtnClickListener = listener;
    }

    public void setOnSeekListener(OnSeekListener listener) {
        this.onSeekListener = listener;
    }

    /**
     * 设置本地播放源
     *
     * @param videoPath 本地播放源
     */
    public void setLocalSource(String videoPath) {
        if (videoPath == null || videoPath.length() == 0) return;
        UrlSource aliyunLocalSource = new UrlSource();
        aliyunLocalSource.setUri(videoPath);
        if (mAliyunVodPlayer == null) {
            return;
        }
        reset();
        mAliyunLocalSource = aliyunLocalSource;
        prepareLocalSource(aliyunLocalSource);
    }

    /**
     * 设置本地播放源
     *
     * @param aliyunLocalSource 本地播放源
     */
    public void setLocalSource(UrlSource aliyunLocalSource) {
        if (mAliyunVodPlayer == null) {
            return;
        }

        clearAllSource();
        reset();

        mAliyunLocalSource = aliyunLocalSource;

        prepareLocalSource(aliyunLocalSource);

    }

    /**
     * prepare本地播放源
     *
     * @param aliyunLocalSource 本地播放源
     */
    private void prepareLocalSource(UrlSource aliyunLocalSource) {

        if (mControlView != null) {
            mControlView.setIsMtsSource(false);
        }


        mAliyunVodPlayer.setAutoPlay(true);
        mAliyunVodPlayer.setDataSource(aliyunLocalSource);
        mAliyunVodPlayer.prepare();
    }

    public void setNetConnectedListener(NetConnectedListener listener) {
        this.mNetConnectedListener = listener;
    }

    public void setOnScreenBrightness(OnScreenBrightnessListener listener) {
        this.mOnScreenBrightnessListener = listener;
    }

    /**
     * 获取当前播放器正在播放的媒体信息
     */
    public MediaInfo getCurrentMediaInfo() {
        return mAliyunMediaInfo;
    }

    public int getScreenBrightness() {
        return this.mScreenBrightness;
    }

    /**
     * 原视频准备完成
     */
    private void sourceVideoPlayerPrepared() {
        //需要将mThumbnailPrepareSuccess重置,否则会出现缩略图错乱的问题
        mThumbnailPrepareSuccess = false;

        if (mAliyunVodPlayer == null) {
            return;
        }
        mAliyunMediaInfo = mAliyunVodPlayer.getMediaInfo();

        if (mAliyunMediaInfo == null) {
            return;
        }

        //防止服务器信息和实际不一致
        mSourceDuration = mAliyunVodPlayer.getDuration();
        mAliyunMediaInfo.setDuration((int) mSourceDuration);

        if (mControlView != null) {
            mControlView.setMediaInfo(mAliyunMediaInfo, "FD");
            mControlView.setHideType(ViewAction.HideType.Normal);
        }
        mSurfaceView.setVisibility(View.VISIBLE);

        //准备成功之后可以调用start方法开始播放
        if (mOutPreparedListener != null) {
            mOutPreparedListener.onPrepared();
        }
    }

    /**
     * 原视频错误监听
     */
    private void sourceVideoPlayerError(ErrorInfo errorInfo) {


        //errorInfo.getExtra()展示为null,修改为显示errorInfo.getCode的十六进制的值
        showErrorTipView(errorInfo.getCode().getValue(), Integer.toHexString(errorInfo.getCode().getValue()), errorInfo.getMsg());

        if (mOutErrorListener != null) {
            mOutErrorListener.onError(errorInfo);
        }
    }

    /**
     * 原视频开始加载进度
     */
    private void sourceVideoPlayerLoadingProgress(int percent) {

    }

    /**
     * 原视频加载结束
     */
    private void sourceVideoPlayerLoadingEnd() {

        hasLoadEnd.put(mAliyunMediaInfo, true);
        vodPlayerLoadEndHandler.sendEmptyMessage(1);
    }

    /**
     * 原视频状态改变监听
     */
    private void sourceVideoPlayerStateChanged(int newState) {
        mPlayerState = newState;
        if (newState == IPlayer.stopped) {
            if (mOnStoppedListener != null) {
                mOnStoppedListener.onStop();
            }
        } else if (newState == IPlayer.started) {
            if (mControlView != null) {
                mControlView.setPlayState(ControlView.PlayState.Playing);
            }
        }
    }

    /**
     * 原视频播放完成
     */
    private void sourceVideoPlayerCompletion() {
        inSeek = false;
        //如果当前播放资源是本地资源时, 再显示replay
        if (mOutCompletionListener != null) {
            mOutCompletionListener.onCompletion();
        }
        mCurVideoIdx++;
        if (mCurVideoIdx == mVideoSourceList.size()) {
            mCurVideoIdx = 0;
        }
        setLocalSource(mVideoSourceList.get(mCurVideoIdx));
    }

    /**
     * 原视频Info
     */
    private void sourceVideoPlayerInfo(InfoBean infoBean) {
        if (infoBean.getCode() == InfoCode.AutoPlayStart) {
            //自动播放开始,需要设置播放状态
            if (mControlView != null) {
                mControlView.setPlayState(ControlView.PlayState.Playing);
            }

        } else if (infoBean.getCode() == InfoCode.BufferedPosition) {
            //更新bufferedPosition
            mVideoBufferedPosition = infoBean.getExtraValue();
            if (mControlView != null)
                mControlView.setVideoBufferPosition((int) mVideoBufferedPosition);
        } else if (infoBean.getCode() == InfoCode.CurrentPosition) {
            //更新currentPosition
            mCurrentPosition = infoBean.getExtraValue();
            if (mControlView != null && !inSeek && mPlayerState == IPlayer.started) {
                mControlView.setVideoPosition((int) mCurrentPosition);
            }
        } else if (infoBean.getCode() == InfoCode.AutoPlayStart) {
            //自动播放开始,需要设置播放状态
            if (mControlView != null) {
                mControlView.setPlayState(ControlView.PlayState.Playing);
            }

        } else {
            if (mOutInfoListener != null) {
                mOutInfoListener.onInfo(infoBean);
            }
        }
    }

    /**
     * 原视频onVideoRenderingStart
     */
    private void sourceVideoPlayerOnVideoRenderingStart() {
        if (mCoverView != null)
            mCoverView.setVisibility(GONE);
        if (mOutFirstFrameStartListener != null) {
            mOutFirstFrameStartListener.onRenderingStart();
        }
    }

    public PlayerConfig getPlayerConfig() {
        if (mAliyunVodPlayer != null) {
            return mAliyunVodPlayer.getConfig();
        }
        return null;
    }

    /**
     * 设置延迟时间
     */
    public void setPlayerConfig() {
        PlayerConfig playerConfig = getPlayerConfig();
        //默认是5000
        int maxDelayTime = 500;
        if (PlayParameter.PLAY_PARAM_URL.startsWith("artp")) {
            //如果url的开头是artp，将直播延迟设置成100，
            maxDelayTime = 100;
        }
        playerConfig.mMaxDelayTime = maxDelayTime;
        if (mAliyunVodPlayer != null) {
            mAliyunVodPlayer.setConfig(playerConfig);
        }
    }

    /**
     * 原视频 trackInfochangedFail
     */
    private void sourceVideoPlayerTrackInfoChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
        //失败的话，停止播放，通知上层
        stop();
    }

    /**
     * ------------------- 播放器回调 ---------------------------
     */

    /**
     * 原视频seek完成
     */
    private void sourceVideoPlayerSeekComplete() {
        inSeek = false;

        if (mOuterSeekCompleteListener != null) {
            mOuterSeekCompleteListener.onSeekComplete();
        }
    }

    /**
     * ------------------- 播放器回调 end---------------------------
     */

    private void hideSystemUI() {
        VideoPlayerView.this.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }

    public void setOnSwitchScreenModeStatus(OnSwitchScreenModeStatus onSwitchScreenModeStatus) {
        this.onSwitchScreenModeStatus = onSwitchScreenModeStatus;
    }

    public void setDetails() {
        mControlView.setDetails();
    }

    public void setLikeDetails() {
        mControlView.setLikeDetails();
    }

    public void setVideoSourceList(List<String> mVideoSourceList) {
        this.mVideoSourceList = mVideoSourceList;
    }

    /**
     * Player View Click Type
     */
    public enum PlayViewType {
        /**
         * click download view
         */
        Download,
        /**
         * click screen cast
         */
        ScreenCast
    }

    public interface OnTimeExpiredErrorListener {
        void onTimeExpiredError();
    }


    public interface OnBackListener {
        void onBackListener();
    }

    /**
     * 播放按钮点击listener
     */
    public interface OnPlayStateBtnClickListener {
        void onPlayBtnClick(int playerState);
    }

    /**
     * seek开始监听
     */

    public interface OnSeekListener {
        void onSeekStart(int position);

        void onSeekComplete(int position);
    }

    /**
     * 判断是否有网络的监听
     */
    public interface NetConnectedListener {
        /**
         * 网络已连接
         */
        void onReNetConnected(boolean isReconnect);

        /**
         * 网络未连接
         */
        void onNetUnConnected();
    }

    public interface OnFinishListener {
        void onFinishClick();
    }

    /**
     * 横屏下显示更多
     */
    public interface OnShowMoreClickListener {
        void showMore();
    }

    public interface OnScreenBrightnessListener {
        void onScreenBrightness(int brightness);
    }

    public interface OnSwitchScreenModeStatus {
        /**
         * 切换大小屏幕
         *
         * @param currentMode 当前模式
         */
        void Switch(ScreenMode currentMode);
    }

    private static class MyNetChangeListener implements NetWatchdog.NetChangeListener {

        private WeakReference<VideoPlayerView> viewWeakReference;

        public MyNetChangeListener(VideoPlayerView videoPlayerView) {
            viewWeakReference = new WeakReference<VideoPlayerView>(videoPlayerView);
        }

        @Override
        public void onWifiTo4G() {
            VideoPlayerView videoPlayerView = viewWeakReference.get();
        }

        @Override
        public void on4GToWifi() {
            VideoPlayerView videoPlayerView = viewWeakReference.get();
        }

        @Override
        public void onNetDisconnected() {
            VideoPlayerView videoPlayerView = viewWeakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.onNetDisconnected();
            }
        }
    }

    /**
     * 当VodPlayer 没有加载完成的时候,调用onStop 去暂停视频,
     * 会出现暂停失败的问题。
     */
    private static class VodPlayerLoadEndHandler extends Handler {

        private WeakReference<VideoPlayerView> weakReference;

        private boolean intentPause;

        public VodPlayerLoadEndHandler(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                intentPause = true;
            }
            if (msg.what == 1) {
                VideoPlayerView videoPlayerView = weakReference.get();
                if (videoPlayerView != null && intentPause) {
                    videoPlayerView.onStop();
                    intentPause = false;
                }
            }
        }
    }

    /**
     * 广告视频播放器准备对外接口监听
     */
    public static class VideoPlayerPreparedListener implements IPlayer.OnPreparedListener {

        private WeakReference<VideoPlayerView> weakReference;

        public VideoPlayerPreparedListener(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }

        @Override
        public void onPrepared() {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerPrepared();
            }
        }
    }

    private static class VideoPlayerErrorListener implements IPlayer.OnErrorListener {

        private WeakReference<VideoPlayerView> weakReference;

        public VideoPlayerErrorListener(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }

        @Override
        public void onError(ErrorInfo errorInfo) {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerError(errorInfo);
            }
        }
    }

    /**
     * 播放器加载状态监听
     */
    private static class VideoPlayerLoadingStatusListener implements IPlayer.OnLoadingStatusListener {

        private WeakReference<VideoPlayerView> weakReference;

        public VideoPlayerLoadingStatusListener(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }

        @Override
        public void onLoadingBegin() {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
            }
        }

        @Override
        public void onLoadingProgress(int percent, float v) {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerLoadingProgress(percent);
            }
        }

        @Override
        public void onLoadingEnd() {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerLoadingEnd();
            }
        }
    }

    /**
     * 播放器状态改变监听
     */
    private static class VideoPlayerStateChangedListener implements IPlayer.OnStateChangedListener {

        private WeakReference<VideoPlayerView> weakReference;

        public VideoPlayerStateChangedListener(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }


        @Override
        public void onStateChanged(int newState) {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerStateChanged(newState);
            }
        }
    }

    /**
     * 播放器播放完成监听
     */
    private static class VideoPlayerCompletionListener implements IPlayer.OnCompletionListener {

        private WeakReference<VideoPlayerView> weakReference;

        public VideoPlayerCompletionListener(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }

        @Override
        public void onCompletion() {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerCompletion();
            }
        }
    }

    /**
     * 播放器Info监听
     */
    private static class VideoPlayerInfoListener implements IPlayer.OnInfoListener {

        private WeakReference<VideoPlayerView> weakReference;

        public VideoPlayerInfoListener(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }

        @Override
        public void onInfo(InfoBean infoBean) {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerInfo(infoBean);
            }
        }
    }

    /**
     * 播放器Render监听
     */
    private static class VideoPlayerRenderingStartListener implements IPlayer.OnRenderingStartListener {

        private WeakReference<VideoPlayerView> weakReference;

        public VideoPlayerRenderingStartListener(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }

        @Override
        public void onRenderingStart() {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerOnVideoRenderingStart();
            }
        }
    }

    /**
     * 播放器TrackChanged监听
     */
    private static class VideoPlayerTrackChangedListener implements IPlayer.OnTrackChangedListener {

        private WeakReference<VideoPlayerView> weakReference;

        public VideoPlayerTrackChangedListener(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }

        @Override
        public void onChangedSuccess(TrackInfo trackInfo) {
            VideoPlayerView videoPlayerView = weakReference.get();
        }

        @Override
        public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerTrackInfoChangedFail(trackInfo, errorInfo);
            }
        }
    }

    /**
     * 播放器seek完成监听
     */
    private static class VideoPlayerOnSeekCompleteListener implements IPlayer.OnSeekCompleteListener {

        private WeakReference<VideoPlayerView> weakReference;

        public VideoPlayerOnSeekCompleteListener(VideoPlayerView videoPlayerView) {
            weakReference = new WeakReference<>(videoPlayerView);
        }

        @Override
        public void onSeekComplete() {
            VideoPlayerView videoPlayerView = weakReference.get();
            if (videoPlayerView != null) {
                videoPlayerView.sourceVideoPlayerSeekComplete();
            }
        }
    }

    /**
     * 断网/连网监听
     */
    private class MyNetConnectedListener implements NetWatchdog.NetConnectedListener {
        public MyNetConnectedListener(VideoPlayerView videoPlayerView) {
        }

        @Override
        public void onReNetConnected(boolean isReconnect) {
            if (mNetConnectedListener != null) {
                mNetConnectedListener.onReNetConnected(isReconnect);
            }
        }

        @Override
        public void onNetUnConnected() {
            if (mNetConnectedListener != null) {
                mNetConnectedListener.onNetUnConnected();
            }
        }
    }
}
